package timing.ukulele.third.msgChannel.handle.impl;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import timing.ukulele.third.dictionary.msg.MsgChannelType;
import timing.ukulele.third.dictionary.msg.SendMessageType;
import timing.ukulele.third.msgChannel.handle.BaseHandler;
import timing.ukulele.third.msgChannel.model.RecallTaskInfo;
import timing.ukulele.third.msgChannel.model.SendTaskInfo;
import timing.ukulele.third.msgChannel.model.account.FeiShuRobotAccount;
import timing.ukulele.third.msgChannel.model.content.FeiShuRobotContentModel;
import timing.ukulele.third.msgChannel.param.HandleMessageBaseResponse;
import timing.ukulele.third.msgChannel.param.feishu.FeiShuRobotParam;
import timing.ukulele.third.msgChannel.param.feishu.FeiShuRobotResult;
import timing.ukulele.third.msgChannel.utils.AccountUtils;
import java.util.ArrayList;
import java.util.List;

/**
 * 飞书自定义机器人 消息处理器
 * https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
 * @author zh
 */
@Slf4j
@Service
public class FeiShuRobotHandler extends BaseHandler {

    @Autowired
    private AccountUtils accountUtils;

    public FeiShuRobotHandler() {
        channelCode = MsgChannelType.FEI_SHU_ROBOT.getCode();
    }

    @Override
    public HandleMessageBaseResponse send(SendTaskInfo taskInfo) {
        // 构造返回值
        HandleMessageBaseResponse result = new HandleMessageBaseResponse();
        try {
            FeiShuRobotAccount account = accountUtils.getAccountById(
                    taskInfo.getSendAccountId(), FeiShuRobotAccount.class);
            FeiShuRobotParam feiShuRobotParam = assembleParam(taskInfo);
            String requestResponse = HttpRequest.post(account.getWebhook())
                    .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
                    .body(JSON.toJSONString(feiShuRobotParam))
                    .timeout(2000)
                    .execute().body();
            log.info("FeiShuRobotHandler#send response:{}, params:{}", requestResponse, JSON.toJSONString(taskInfo));
            FeiShuRobotResult feiShuRobotResult = JSON.parseObject(requestResponse, FeiShuRobotResult.class);
            if (feiShuRobotResult.getStatusCode() == 0) {
                result.setHandleFlag(true);
            }else{
                result.setHandleFlag(false);
            }
            result.setHandleMessage(feiShuRobotResult.getStatusMessage());
        } catch (Exception e) {
            log.error("FeiShuRobotHandler#send fail!e:{}, params:{}", Throwables.getStackTraceAsString(e), JSON.toJSONString(taskInfo));
            result.setHandleFlag(false);
        }
        return result;
    }

    /**
     * 飞书自定义机器人 暂只支持文本消息下发，其他的消息类型的组装参数过于复杂。
     *
     * @param taskInfo
     * @return
     */
    private FeiShuRobotParam assembleParam(SendTaskInfo taskInfo) {
        FeiShuRobotContentModel contentModel = (FeiShuRobotContentModel) taskInfo.getContentModel();

        FeiShuRobotParam param = FeiShuRobotParam.builder()
                .msgType(SendMessageType.geFeiShuRobotTypeByCode(contentModel.getSendType())).build();

        if (SendMessageType.TEXT.getCode().equals(contentModel.getSendType())) {
            param.setContent(FeiShuRobotParam.ContentDTO.builder().text(contentModel.getContent()).build());
        }
        if (SendMessageType.RICH_TEXT.getCode().equals(contentModel.getSendType())) {
            List<FeiShuRobotParam.ContentDTO.PostDTO.ZhCnDTO.PostContentDTO> postContentDtoS = JSON.parseArray(contentModel.getPostContent(), FeiShuRobotParam.ContentDTO.PostDTO.ZhCnDTO.PostContentDTO.class);
            List<List<FeiShuRobotParam.ContentDTO.PostDTO.ZhCnDTO.PostContentDTO>> postContentList = new ArrayList<>();
            postContentList.add(postContentDtoS);
            FeiShuRobotParam.ContentDTO.PostDTO postDTO = FeiShuRobotParam.ContentDTO.PostDTO.builder()
                    .zhCn(FeiShuRobotParam.ContentDTO.PostDTO.ZhCnDTO.builder().title(contentModel.getTitle()).content(postContentList).build())
                    .build();
            param.setContent(FeiShuRobotParam.ContentDTO.builder().post(postDTO).build());
        }
        if (SendMessageType.SHARE_CHAT.getCode().equals(contentModel.getSendType())) {
            param.setContent(FeiShuRobotParam.ContentDTO.builder().shareChatId(contentModel.getMediaId()).build());
        }
        if (SendMessageType.IMAGE.getCode().equals(contentModel.getSendType())) {
            param.setContent(FeiShuRobotParam.ContentDTO.builder().imageKey(contentModel.getMediaId()).build());
        }
        if (SendMessageType.ACTION_CARD.getCode().equals(contentModel.getSendType())) {
            //
        }
        return param;
    }

    /**
     * 飞书自定义机器人 不支持撤回消息
     * https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot
     * @param recallTaskInfo
     */
    @Override
    public HandleMessageBaseResponse recall(RecallTaskInfo recallTaskInfo) {
        return HandleMessageBaseResponse.builder().handleFlag(true).build();
    }

}

